import java.text.SimpleDateFormat;
import java.util.*;

public class Staff extends User {

    public Staff(String ID, String password, String name, String date, String tel) {
        super(ID, password, name, date, tel);
        setUserType(LoginKey.STAFF);
    }

    public void staffOperator() {
        boolean exit = false;
        while (!exit) {
            switch (staffMenu()) {
                case "1": //列出所有正在上映的影片
                    showAllShowFilms();
                    break;
                case "2": //列出所有场次
                    showAllSchedule();
                    break;
                case "3": //列出指定电影某场次的座位信息
                    showFilmSchedule();
                    break;
                case "4": //售票
                    salesTicket();
                    break;
                case "5": //退票
                    returnTicket();
                    break;
                case "0":
                    exit = true;
                    break;
            }
        }
    }

    private void showAllShowFilms() {
        System.out.println("已上映的电影信息如下：");
        for (Film film : CinemaSystem.filmsList) {
            System.out.print("电影名：" + film.getName());
            System.out.println("\t" + "导演：" + film.getDirector());
            System.out.println("\t" + "主演：" + film.getMainCharacter());
            System.out.println("\t" + "剧情简介：" + film.getSynopsis());
            System.out.println("\t" + "时长：" + film.getLength());
            System.out.println("\t" + "评分：" + film.getScore());
            System.out.println("\t" + "基础价格：" + film.getBasicPrice());
            System.out.print("\n");
        }
    }

    private void showAllSchedule() {
        if (CinemaSystem.schedules.isEmpty()) {
            System.out.println("当前无排片记录");
            return;
        }

        System.out.println("当前所有排片：");
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        for (Schedule s : CinemaSystem.schedules) {
            System.out.printf(
                    "%-8s | %-10s | %s-%s | 《%s》 | ¥%.1f\n",
                    s.getHall().getType(),
                    sdf.format(s.getStartTime()),
                    sdf.format(s.getStartTime()),
                    sdf.format(s.getEndTime()),
                    s.getFilm().getName(),
                    s.getFinalPrice()
            );
        }
    }

    private void showFilmSchedule() {
        if (CinemaSystem.schedules.isEmpty()) {
            System.out.println("当前没有排片！");
            return;
        }

        // 先让用户选择电影
        System.out.println("\n=== 选择电影 ===");
        Set<String> filmNames = new HashSet<>();
        for (Schedule schedule : CinemaSystem.schedules) {
            filmNames.add(schedule.getFilm().getName());
        }

        List<String> filmList = new ArrayList<>(filmNames);
        for (int i = 0; i < filmList.size(); i++) {
            System.out.println((i + 1) + ". " + filmList.get(i));
        }

        System.out.print("请选择电影编号：");
        int filmChoice = input.nextInt() - 1;
        if (filmChoice < 0 || filmChoice >= filmList.size()) {
            System.out.println("无效选择！");
            return;
        }

        String selectedFilm = filmList.get(filmChoice);

        // 显示该电影的所有场次
        List<Schedule> filmSchedules = new ArrayList<>();
        System.out.println("\n=== " + selectedFilm + " 的场次 ===");
        for (Schedule schedule : CinemaSystem.schedules) {
            if (schedule.getFilm().getName().equals(selectedFilm)) {
                filmSchedules.add(schedule);
            }
        }

        for (int i = 0; i < filmSchedules.size(); i++) {
            Schedule schedule = filmSchedules.get(i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            System.out.printf("%d. %s %s ¥%.1f\n",
                    i + 1,
                    schedule.getHall().getType(),
                    sdf.format(schedule.getStartTime()),
                    schedule.getFinalPrice());
        }

        System.out.print("请选择场次编号：");
        int scheduleChoice = input.nextInt() - 1;
        if (scheduleChoice < 0 || scheduleChoice >= filmSchedules.size()) {
            System.out.println("无效选择！");
            return;
        }

        Schedule selectedSchedule = filmSchedules.get(scheduleChoice);
        displaySeatInfo(selectedSchedule);
    }

    // 显示座位信息
    private void displaySeatInfo(Schedule schedule) {
        ScreeningHall hall = schedule.getHall();
        Set<String> soldSeats = schedule.getSoldSeats();

        System.out.println("\n=== 座位信息 ===");
        System.out.println("影厅：" + hall.getType() + "，容量：" + hall.getCapacity() + "座");
        System.out.println("已售座位：" + soldSeats.size() + "，剩余座位：" + (hall.getCapacity() - soldSeats.size()));

        // 显示座位图（简单版本）
        System.out.println("\n座位状态：○ 可选  ● 已售");
        for (int i = 1; i <= hall.getCapacity(); i++) {
            String seat = "座位" + i;
            if (soldSeats.contains(seat)) {
                System.out.print("● ");
            } else {
                System.out.print("○ ");
            }

            if (i % 10 == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }

    private void salesTicket() {
        if (CinemaSystem.schedules.isEmpty()) {
            System.out.println("当前没有排片！");
            return;
        }

        showAllSchedule();
        System.out.print("\n请选择要购票的场次编号：");
        int scheduleIdx = input.nextInt() - 1;

        if (scheduleIdx < 0 || scheduleIdx >= CinemaSystem.schedules.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Schedule schedule = CinemaSystem.schedules.get(scheduleIdx);
        ScreeningHall hall = schedule.getHall();

        // 检查是否满座
        if (schedule.getSoldSeats().size() >= hall.getCapacity()) {
            System.out.println("该场次已满座！");
            return;
        }

        // 显示座位信息
        displaySeatInfo(schedule);

        // 选择座位
        System.out.print("请输入要购买的座位号（如：座位1）：");
        input.nextLine(); // 消耗换行符
        String seatNumber = input.nextLine();

        // 检查座位是否已售
        if (schedule.getSoldSeats().contains(seatNumber)) {
            System.out.println("该座位已售出！");
            return;
        }

        // 确认购票
        System.out.printf("确认购买 %s %s 的票？(Y/N)：",
                schedule.getFilm().getName(), seatNumber);
        String confirm = input.next();

        if (confirm.equalsIgnoreCase("Y")) {
            schedule.getSoldSeats().add(seatNumber);
            System.out.println("购票成功！票价：¥" + schedule.getFinalPrice());
        } else {
            System.out.println("取消购票");
        }
    }

    private void returnTicket() {
        System.out.print("请输入要退票的场次编号：");
        int scheduleIdx = input.nextInt() - 1;

        if (scheduleIdx < 0 || scheduleIdx >= CinemaSystem.schedules.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Schedule schedule = CinemaSystem.schedules.get(scheduleIdx);

        if (schedule.getSoldSeats().isEmpty()) {
            System.out.println("该场次暂无售出票！");
            return;
        }

        System.out.println("已售座位：" + schedule.getSoldSeats());
        System.out.print("请输入要退票的座位号：");
        input.nextLine(); // 消耗换行符
        String seatNumber = input.nextLine();

        if (!schedule.getSoldSeats().contains(seatNumber)) {
            System.out.println("该座位未售出！");
            return;
        }

        System.out.print("确认退票？(Y/N)：");
        String confirm = input.next();

        if (confirm.equalsIgnoreCase("Y")) {
            schedule.getSoldSeats().remove(seatNumber);
            System.out.println("退票成功！退款金额：¥" + schedule.getFinalPrice());
        } else {
            System.out.println("取消退票");
        }
    }

    private String staffMenu() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 列出所有正在上映影片的信息");
        System.out.println("2. 列出所有场次的信息");
        System.out.println("3. 列出指定电影和场次的信息");
        System.out.println("4. 售票");
        System.out.println("5. 退票");
        System.out.println("0. 退出登录");
        System.out.println("请选择：");
        String choice;
        boolean right;
        do {
            choice = input.next();
            right = choice.equals("1") || choice.equals("2") || choice.equals("3") ||
                    choice.equals("4") || choice.equals("5") || choice.equals("0");
            if (!right) System.out.println("输入错误，请重新输入：");
        } while (!right);
        return choice;
    }
}